package com.axsoft.jobimp.types;


/**
 * 
 * @author RankoR
 *
 * Abstract data type
 */
public abstract class DataType {

	protected byte[] mData;
	private final int mTypeSize;

	public DataType(final int pSize) {
		clearData();
		mTypeSize = pSize;
		constructData();
	}
	
	
	public void clearData() {
		mData = null;
	}
	
	/**
	 * Allocate memory for mData & set it to 0x00.
	 */
	private void constructData() {
		if (mTypeSize == 0) {
			return;
		}
		
		mData = new byte[mTypeSize];
		
		for (int i = 0; i < mData.length; i++) {
			mData[i] = 0x00;
		}
	}
	
	/**
	 * Get mData length
	 */
	public final int getLength() {
		if (mData != null) {
			return mData.length;
		} else {
			return 0;
		}
	}
	
	
	/**
	 * Get mData 
	 */
	public final byte[] getData() {
		return mData;
	}
	
	/**
	 * Get byte at the given index
	 */
	public byte getByte(final int pIndex) {
		return mData[pIndex];
	}
	
	/**
	 * Set byte at the given index to the given value
	 */
	public void setByte(final int pIndex, final byte pByte) {
		mData[pIndex] = pByte;
	}
	
	/**
	 * Set data by the given array
	 */
	public void setData(final byte[] pData) {
		mData = pData.clone();
	}
	
	/**
	 * Parses byte array to the long integer.
	 * Attention: The pBytes length MUST equal to the type size!
	 */
	protected long parseByteArray(final byte[] pBytes) {
		long value = 0;
		
		for (int i = 0; i < pBytes.length - 1; i++) {
			value |= pBytes[i] & 0xFF;
			value <<= 8;
		}
		
		value |= pBytes[pBytes.length - 1] & 0xFF;
		
		return value;
	}
}
